using System.Collections.Generic;
using System.ComponentModel;
using System.Security.Cryptography;
using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// 背景循环脚本，支持不同宽度的背景对象，根据指定摄像机视角进行滚动
/// </summary>
public class BackgroundLoop : MonoBehaviour
{
    public GameObject[] backgrounds; // 背景对象数组
    public float speed = 5f; // 滚动速度
    public bool moveLeft = true; // 控制滚动方向
    public Camera camera; // 指定的摄像机，用于检测背景对象的视口边界
    public bool isPaused = true; // 是否暂停

    public ParticleSystem BreezePS;

    private int ScenceBgIndex => GameManager.Instance.Level;
    private void Awake()
    {
        EventManager.Instance.Register<bool>(EventName.GameOverEvent, SetPaused);
    }

    private void OnDestroy()
    {
        EventManager.Instance.Unregister<bool>(EventName.GameOverEvent, SetPaused);
    }


    private void Start()
    {
        SetScenceBg();
        if (backgrounds.Length < 2)
        {
            Debug.LogError("需要至少两个背景对象来实现无缝滚动。");
            return;
        }

        if (camera == null)
        {
            Debug.LogError("请为脚本指定一个摄像机对象。");
            return;
        }
        BreezePS.gameObject.SetActive(true);
        BreezePS.Play();
        // 暂时禁用暂停功能，确保背景初始时无缝排列
        bool originalPauseState = isPaused;
        isPaused = false;

        // 初始排列背景对象，确保它们在起始时无缝衔接
        ArrangeBackgrounds();

        // 恢复暂停状态
        isPaused = originalPauseState;

    }

    // 外部调用，用于暂停和继续滚动
    public void SetPaused(bool pause)
    {
        isPaused = pause;
        if (!pause)
        {
            BreezePS.Play();
        }
        else
        {
            BreezePS.Stop();
            for (int i = 0; i < backgrounds.Length; i++)
            {
                Debug.Log($"第{i}个图的坐标:{backgrounds[i].transform.position.x}");
            }

        }
    }

    private List<GameObject> outOfViewBackgrounds = new(); // 存储超出视口的背景对象

    private void Update()
    {
        if (isPaused) return;

        speed = GameManager.Instance.isJiaSu ? 6f : 3f;

        float direction = moveLeft ? -1 : 1;
        Vector3 moveVector = Vector3.right * direction * speed * Time.deltaTime;

        // 懒汉式清理，只有当列表中有元素时才清理
        if (outOfViewBackgrounds.Count > 0)
        {
            outOfViewBackgrounds.Clear();
        }

        // 移动并检测超出视口的背景对象
        foreach (GameObject background in backgrounds)
        {
            background.transform.position += moveVector;

            // 检查背景是否移出视口
            float backgroundWidth = background.GetComponent<SpriteRenderer>().bounds.size.x;
            if ((moveLeft && IsOutOfViewLeft(background, backgroundWidth)) || (!moveLeft && IsOutOfViewRight(background, backgroundWidth)))
            {
                // 将需要重定位的背景对象添加到列表
                outOfViewBackgrounds.Add(background);
            }
        }

        // 如果有超出视口的背景对象，进行重定位
        if (outOfViewBackgrounds.Count > 0)
        {
            foreach (var background in outOfViewBackgrounds)
            {
                RepositionBackground(background);
            }
        }
    }


    /// <summary>
    /// 初始化时调整 当前图  已列表第一个元素为起点
    /// </summary>
    private void ArrangeBackgrounds()
    {
        Transform lastBackgroundTransform = backgrounds[0].transform;
        float lastWidth = lastBackgroundTransform.GetComponent<SpriteRenderer>().bounds.size.x;
        for (int i = 1; i < backgrounds.Length; i++)
        {
            float currentWidth = backgrounds[i].GetComponent<SpriteRenderer>().bounds.size.x;

            float offset = (lastWidth + currentWidth) / 2;
            backgrounds[i].transform.position = new Vector3(
                lastBackgroundTransform.position.x + offset,
                backgrounds[i].transform.position.y,
                backgrounds[i].transform.position.z
            );
            lastBackgroundTransform = backgrounds[i].transform;
            lastWidth = currentWidth;
        }
    }


    private bool IsOutOfViewLeft(GameObject background, float backgroundWidth)
    {
        // 检测背景是否完全移出摄像机左侧视口
        float rightEdge = background.transform.position.x + backgroundWidth / 2;
        float camLeftEdge = camera.transform.position.x - camera.orthographicSize * camera.aspect;
        return rightEdge < camLeftEdge;
    }

    private bool IsOutOfViewRight(GameObject background, float backgroundWidth)
    {
        // 检测背景是否完全移出摄像机右侧视口
        float leftEdge = background.transform.position.x - backgroundWidth / 2;
        float camRightEdge = camera.transform.position.x + camera.orthographicSize * camera.aspect;
        return leftEdge > camRightEdge;
    }

    private void RepositionBackground(GameObject background)
    {
        // 找到最远的背景对象，用于无缝衔接
        GameObject farthestBackground = backgrounds[0];
        foreach (GameObject bg in backgrounds)
        {
            if (moveLeft && bg.transform.position.x > farthestBackground.transform.position.x)
            {
                farthestBackground = bg;
            }
            else if (!moveLeft && bg.transform.position.x < farthestBackground.transform.position.x)
            {
                farthestBackground = bg;
            }
        }

        // 动态获取背景宽度，确保无缝衔接
        float backgroundWidth = background.GetComponent<SpriteRenderer>().bounds.size.x;
        float farthestBackgroundWidth = farthestBackground.GetComponent<SpriteRenderer>().bounds.size.x;

        var value = (backgroundWidth + farthestBackgroundWidth) / 2;
        // 将移出视口的背景对象放置到最远背景的右侧或左侧
        value -= 0.05f;
        if (moveLeft)
        {
            background.transform.position = new Vector3(
                farthestBackground.transform.position.x + value,
                background.transform.position.y,
                background.transform.position.z
            );
        }
        else
        {
            background.transform.position = new Vector3(
                farthestBackground.transform.position.x - value,
                background.transform.position.y,
                background.transform.position.z
            );
        }
    }

    /// <summary>
    /// 背景图片命名规则 :SceneBg_第几个场景_当前场景的第几个_上边还是下边  
    /// </summary>
    public void SetScenceBg()
    {
        for (int i = 0; i < backgrounds.Length; i++)
        {
            //backgrounds[i].transform.GetComponent<SpriteRenderer>().sprite = ResManager.LoadAsset<Sprite>(ResPathDefine.IMAGE_PREFIX + $"SenceBg/SceneBg_{ScenceBgIndex}_{i + 1}_1");
            //backgrounds[i].transform.Find("Item").GetComponent<SpriteRenderer>().sprite = ResManager.Instance.LoadAsset<Sprite>(ResPathDefine.IMAGE_PREFIX + $"SenceBg/SceneBg_{ScenceBgIndex}_{i + 1}_0");

            backgrounds[i].transform.GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>($"Image/SenceBg/SceneBg_{ScenceBgIndex}_{i + 1}_1");
            backgrounds[i].transform.Find("Item").GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>($"Image/SenceBg/SceneBg_{ScenceBgIndex}_{i + 1}_0");
        }
    }

}